package com.zzyl.framework.interceptor;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.zzyl.common.core.domain.model.LoginUser;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.SecurityUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    @Autowired
    HttpServletRequest httpServletRequest;
    
    /**
     * 定义一个方法用来判断是否要填充对应字段
     * false： 不给字段填充属性
     * true： 给字段填充属性值
     */
    public boolean isFill() {
        try {
            String requestURI=httpServletRequest.getRequestURI();
            if (requestURI.startsWith("/member")) {
                return false;
            }
            return true;
        } catch (Exception e) {
            return false;
        }
    }
    
    // 插入数据时自动填充
    @Override
    public void insertFill(MetaObject metaObject) {
        if (isFill()) {
            this.strictInsertFill(metaObject,"createBy",String.class,String.valueOf(getLoginUserId()));
        }
        this.strictInsertFill(metaObject,"createTime",Date.class,DateUtils.getNowDate());
    }
    
    // 修改数据时自动填充
    @Override
    public void updateFill(MetaObject metaObject) {
        if (isFill()) {
            this.setFieldValByName("updateBy",String.valueOf(getLoginUserId()),metaObject);
        }
        this.setFieldValByName("updateTime",DateUtils.getNowDate(),metaObject);
    }
    
    // 获取当前登录人的id
    public Long getLoginUserId() {
        LoginUser loginUser=SecurityUtils.getLoginUser();
        if (ObjectUtils.isNotEmpty(loginUser)) {
            return loginUser.getUserId();
        }
        return 1L;
    }
}
